package com.oa.jx.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.jx.entity.JxAssessScheme;
import com.oa.jx.entity.JxAssessSchemeExec;
import com.oa.jx.service.JxAssessGradeService;
import com.oa.jx.service.JxAssessSchemeExecService;
import com.oa.jx.service.JxAssessSchemeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mdp.core.utils.BaseUtils.map;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@RestController
@RequestMapping(value = "/*/oa/jx/jxAssessSchemeExec")
@Api(tags = {"考核方案-操作接口"})
public class JxAssessSchemeExecController {

    static Logger logger = LoggerFactory.getLogger(JxAssessSchemeExecController.class);

    @Autowired
    private JxAssessSchemeExecService jxAssessSchemeExecService;

    @Autowired
    private JxAssessSchemeService jxAssessSchemeService;


    @Autowired
    private JxAssessGradeService jxAssessGradeService;

    @ApiOperation(value = "考核方案-查询列表", notes = " ")
    @ApiEntityParams(JxAssessSchemeExec.class)
    @ApiResponses({@ApiResponse(code = 200, response = JxAssessSchemeExec.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listJxAssessSchemeExec(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");

        QueryWrapper<JxAssessSchemeExec> qw = QueryTools.initQueryWrapper(JxAssessSchemeExec.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = jxAssessSchemeExecService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }


    @ApiOperation(value = "考核方案-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = JxAssessSchemeExec.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addJxAssessSchemeExec(@RequestBody JxAssessSchemeExec jxAssessSchemeExec) {


        boolean createPk = false;
        if (StringUtils.isEmpty(jxAssessSchemeExec.getId())) {
            createPk = true;
            jxAssessSchemeExec.setId(jxAssessSchemeExecService.createKey("id"));
        }
        if (createPk == false) {
            if (jxAssessSchemeExecService.selectOneObject(jxAssessSchemeExec) != null) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        JxAssessSchemeExec query = new JxAssessSchemeExec();
        query.setYear(jxAssessSchemeExec.getYear());
        query.setSchemeId(jxAssessSchemeExec.getSchemeId());
        query.setBranchId(jxAssessSchemeExec.getBranchId());
        if ("0".equals(jxAssessSchemeExec.getSchemeType())) {//月度
            if (!StringUtils.hasText(jxAssessSchemeExec.getMonth())) {
                return Result.error("month-null", "请上送month月份参数");
            }
            query.setMonth(jxAssessSchemeExec.getMonth());
        } else if ("1".equals(jxAssessSchemeExec.getSchemeType())) {//季度
            if (!StringUtils.hasText(jxAssessSchemeExec.getQuarter())) {
                return Result.error("quarter-null", "请上送quarter季度参数");
            }
            query.setQuarter(jxAssessSchemeExec.getQuarter());
        } else if ("2".equals(jxAssessSchemeExec.getSchemeType())) {//半年度
            if (!StringUtils.hasText(jxAssessSchemeExec.getSemiAnnual())) {
                return Result.error("semiAnnual-null", "请上送semiAnnual半年度参数");
            }
            query.setSemiAnnual(jxAssessSchemeExec.getSemiAnnual());
        } else if ("3".equals(jxAssessSchemeExec.getSchemeType())) {//季度
            query.setAnnual("1");
            jxAssessSchemeExec.setAnnual("1");
        }
        JxAssessScheme jxAssessSchemeDb = this.jxAssessSchemeService.selectOneObject(new JxAssessScheme(jxAssessSchemeExec.getSchemeId()));
        if (jxAssessSchemeDb == null) {
            return Result.error("scheme-not-exists", "该考核方案不存在，不允许创建执行计划");
        }
        if (!"1".equals(jxAssessSchemeDb.getStatus())) {
            return Result.error("scheme-status-not-1", "该考核方案未启用，不能创建执行计划");
        }
        List<JxAssessSchemeExec> execsDb = this.jxAssessSchemeExecService.selectListByWhere(query);
        if (execsDb != null && execsDb.size() > 0) {
            return Result.error("plan-exists", "该考核计划已存在，不允许再创建");
        }
        jxAssessSchemeExec.setStatus("0");
        jxAssessSchemeExec.setInitStatus("0");
        jxAssessSchemeExec.setExecStatus("0");
        if (jxAssessSchemeExec.getStartDate() == null) {
            // todo ?
        }
        jxAssessSchemeExecService.insert(jxAssessSchemeExec);
        return Result.ok("add-ok", "添加成功！").setData(jxAssessSchemeExec);
    }

    @ApiOperation(value = "考核方案-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delJxAssessSchemeExec(@RequestBody JxAssessSchemeExec jxAssessSchemeExec) {


        if (!StringUtils.hasText(jxAssessSchemeExec.getId())) {
            return Result.error("id-is-null", "主键不能为空");
        }
        JxAssessSchemeExec jxAssessSchemeExecDb = this.jxAssessSchemeExecService.selectOneObject(jxAssessSchemeExec);
        if (jxAssessSchemeExecDb == null) {
            return Result.error("data-is-null", "数据不存在");
        }
        if (!"0".equals(jxAssessSchemeExecDb.getInitStatus())) {
            return Result.error("initStatus-not-0", "已初始化该方案，不能删除");
        }
        if (!"0".equals(jxAssessSchemeExecDb.getExecStatus())) {
            return Result.error("execStatus-not-0", "方案已执行，不能删除");
        }
        jxAssessSchemeExecService.deleteByPk(jxAssessSchemeExec);

        return Result.ok("del-ok", "删除成功！");
    }

    /***/
    @ApiOperation(value = "批量设置执行计划下的员工数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/batchSetJxAssessGrade", method = RequestMethod.POST)
    public Result batchSetJxAssessGrade(@RequestBody JxAssessSchemeExec jxAssessSchemeExec) {


        if (!StringUtils.hasText(jxAssessSchemeExec.getId())) {
            return Result.error("id-is-null", "主键不能为空");
        }
        JxAssessSchemeExec jxAssessSchemeExecDb = this.jxAssessSchemeExecService.selectOneObject(jxAssessSchemeExec);
        if (jxAssessSchemeExecDb == null) {
            return Result.error("data-is-null", "数据不存在");
        }
        if (!"0".equals(jxAssessSchemeExecDb.getInitStatus())) {
            return Result.error("initStatus-not-0", "已初始化该方案，不能再批量设置员工");
        }
        if (!"0".equals(jxAssessSchemeExecDb.getExecStatus())) {
            return Result.error("execStatus-not-0", "方案已执行，不能再批量设置员工");
        }

        if (!StringUtils.hasText(jxAssessSchemeExecDb.getTemplateId())) {
            return Result.error("templateId-is-null", "该执行方案模板编号为空，不能进行员工设置");
        }
        jxAssessSchemeExecService.batchSetJxAssessGrade(jxAssessSchemeExecDb);
        this.jxAssessSchemeExecService.calcExecDataFromJxGrade(jxAssessSchemeExecDb.getId());

        return Result.ok();
    }

    /***/
    @ApiOperation(value = "开放员工签约", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/startExec", method = RequestMethod.POST)
    public Result startExec(@RequestBody JxAssessSchemeExec jxAssessSchemeExec) {


        if (!StringUtils.hasText(jxAssessSchemeExec.getId())) {
            return Result.error("id-is-null", "主键不能为空");
        }
        JxAssessSchemeExec jxAssessSchemeExecDb = this.jxAssessSchemeExecService.selectOneObject(jxAssessSchemeExec);
        if (jxAssessSchemeExecDb == null) {
            return Result.error("data-is-null", "数据不存在");
        }
        if (!StringUtils.hasText(jxAssessSchemeExecDb.getTemplateId())) {
            return Result.error("templateId-is-null", "该执行方案模板编号为空，不能进行员工设置");
        }
        if (!"0".equals(jxAssessSchemeExecDb.getStatus())) {
            return Result.error("status-not-0", "该执行方案已启动，不能再启动");
        }
        if (!StringUtils.hasText(jxAssessSchemeExecDb.getSchemeId())) {
            return Result.error("schemeId-is-null", "该执行方案所属方案编号为空，不能启动");
        }
        JxAssessScheme jxAssessSchemeDb = this.jxAssessSchemeService.selectOneObject(new JxAssessScheme(jxAssessSchemeExecDb.getSchemeId()));
        if (jxAssessSchemeDb == null) {
            return Result.error("scheme-is-null", "方案已不存在，不能启动");
        }
        if (!"1".equals(jxAssessSchemeDb.getStatus())) {
            return Result.error("scheme-not-1", "方案已关闭，不能再启动");
        }
        Map<String, Object> map = map("schemeExecId", jxAssessSchemeExecDb.getId());
//			PageUtils.startPage(0,3);
        List<Map<String, Object>> grades = this.jxAssessGradeService.selectListNoReUseridOrNoVouchUserid(map);
        Page page = (Page) grades;
        if (page.getTotal() > 0) {
            String assUsernames = grades.stream().map(i -> (String) i.get("assUsername")).collect(Collectors.joining(","));
            return Result.error("reUserid-or-vouchId-null", "存在" + assUsernames + "等" + page.getTotal() + "个员工未设置复评人及核定人，请先设置");
        }
        jxAssessSchemeExecService.startExec(jxAssessSchemeExecDb);

        return Result.ok();
    }


    /***/
    @ApiOperation(value = "关闭执行计划", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/closeExec", method = RequestMethod.POST)
    public Result closeExec(@RequestBody JxAssessSchemeExec jxAssessSchemeExec) {


        if (!StringUtils.hasText(jxAssessSchemeExec.getId())) {
            return Result.error("id-is-null", "主键不能为空");
        }
        JxAssessSchemeExec jxAssessSchemeExecDb = this.jxAssessSchemeExecService.selectOneObject(jxAssessSchemeExec);
        if (jxAssessSchemeExecDb == null) {
            return Result.error("data-is-null", "数据不存在");
        }
        jxAssessSchemeExecService.closeExec(jxAssessSchemeExecDb);

        return Result.ok();
    }

    /***/
    @ApiOperation(value = "暂停执行计划", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/suspendExec", method = RequestMethod.POST)
    public Result suspendExec(@RequestBody JxAssessSchemeExec jxAssessSchemeExec) {


        if (!StringUtils.hasText(jxAssessSchemeExec.getId())) {
            return Result.error("id-is-null", "主键不能为空");
        }
        JxAssessSchemeExec jxAssessSchemeExecDb = this.jxAssessSchemeExecService.selectOneObject(jxAssessSchemeExec);
        if (jxAssessSchemeExecDb == null) {
            return Result.error("data-is-null", "数据不存在");
        }
        if (!"1".equals(jxAssessSchemeExecDb.getStatus())) {
            return Result.error("status-not-1", "当前不属于执行中状态，不能暂停");
        }
        jxAssessSchemeExecService.suspendExec(jxAssessSchemeExecDb);

        return Result.ok();
    }


    /***/
    @ApiOperation(value = "恢复执行计划", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/restartExec", method = RequestMethod.POST)
    public Result restartExec(@RequestBody JxAssessSchemeExec jxAssessSchemeExec) {


        if (!StringUtils.hasText(jxAssessSchemeExec.getId())) {
            return Result.error("id-is-null", "主键不能为空");
        }
        JxAssessSchemeExec jxAssessSchemeExecDb = this.jxAssessSchemeExecService.selectOneObject(jxAssessSchemeExec);
        if (jxAssessSchemeExecDb == null) {
            return Result.error("data-is-null", "数据不存在");
        }
        if (!"3".equals(jxAssessSchemeExecDb.getStatus())) {
            return Result.error("status-not-1", "当前不属于暂停状态，不能重新启动");
        }
        jxAssessSchemeExecService.restartExec(jxAssessSchemeExecDb);

        return Result.ok();
    }


    @ApiOperation(value = "考核方案-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = JxAssessSchemeExec.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editJxAssessSchemeExec(@RequestBody JxAssessSchemeExec jxAssessSchemeExec) {


        if (!StringUtils.hasText(jxAssessSchemeExec.getId())) {
            return Result.error("id-is-null", "主键不能为空");
        }
        JxAssessSchemeExec jxAssessSchemeExecDb = this.jxAssessSchemeExecService.selectOneObject(jxAssessSchemeExec);
        if (jxAssessSchemeExecDb == null) {
            return Result.error("data-is-null", "数据不存在");
        }
        if (jxAssessSchemeExecDb.getSchemeType().equals(jxAssessSchemeExec.getSchemeType())) {
            return Result.error("SchemeType-not-edit", "考核方案类型不能修改");
        }
        if (!jxAssessSchemeExecDb.getYear().equals(jxAssessSchemeExec.getYear())) {
            return Result.error("Year-not-edit", "考核年份不能修改");
        }
        if ("0".equals(jxAssessSchemeExecDb.getSchemeType())) {//月度
            if (!jxAssessSchemeExecDb.getMonth().equals(jxAssessSchemeExec.getMonth())) {
                return Result.error("Month-not-edit", "考核月份不能修改");
            }
        } else if ("1".equals(jxAssessSchemeExecDb.getSchemeType())) {//季度
            if (!jxAssessSchemeExecDb.getQuarter().equals(jxAssessSchemeExec.getQuarter())) {
                return Result.error("Quarter-not-edit", "考核季度不能修改");
            }
        } else if ("2".equals(jxAssessSchemeExecDb.getSchemeType())) {//半年度
            if (!jxAssessSchemeExecDb.getSemiAnnual().equals(jxAssessSchemeExec.getSemiAnnual())) {
                return Result.error("SemiAnnual-not-edit", "考核季度不能修改");
            }

        } else if ("3".equals(jxAssessSchemeExecDb.getSchemeType())) {//年度
            if (!jxAssessSchemeExecDb.getAnnual().equals(jxAssessSchemeExec.getAnnual())) {
                return Result.error("Annual-not-edit", "考核年度不能修改");
            }
        }
        jxAssessSchemeExecService.updateSomeFieldByPk(jxAssessSchemeExec);

        return Result.ok("edit-ok", "修改成功！").setData(jxAssessSchemeExec);
    }

    @ApiOperation(value = "考核方案-批量修改某些字段", notes = "")
    @ApiEntityParams(value = JxAssessSchemeExec.class, props = {}, remark = "考核方案", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = JxAssessSchemeExec.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        jxAssessSchemeExecService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "考核方案-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelJxAssessSchemeExec(@RequestBody List<JxAssessSchemeExec> jxAssessSchemeExecs) {
        User user = LoginUtils.getCurrentUserInfo();
        if (jxAssessSchemeExecs.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<JxAssessSchemeExec> datasDb = jxAssessSchemeExecService.listByIds(jxAssessSchemeExecs.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<JxAssessSchemeExec> can = new ArrayList<>();
        List<JxAssessSchemeExec> no = new ArrayList<>();
        for (JxAssessSchemeExec data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            jxAssessSchemeExecService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "考核方案-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = JxAssessSchemeExec.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(JxAssessSchemeExec jxAssessSchemeExec) {
        JxAssessSchemeExec data = (JxAssessSchemeExec) jxAssessSchemeExecService.getById(jxAssessSchemeExec);
        return Result.ok().setData(data);
    }

}
